package com.YHVision.qiuzhike.controller;

import cn.dev33.satoken.annotation.SaCheckRole;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.YHVision.qiuzhike.annotation.AuthCheck;
import com.YHVision.qiuzhike.common.BaseResponse;
import com.YHVision.qiuzhike.common.DeleteRequest;
import com.YHVision.qiuzhike.common.ErrorCode;
import com.YHVision.qiuzhike.common.ResultUtils;
import com.YHVision.qiuzhike.constant.UserConstant;
import com.YHVision.qiuzhike.exception.BusinessException;
import com.YHVision.qiuzhike.exception.ThrowUtils;
import com.YHVision.qiuzhike.model.dto.company.CompanyAddRequest;
import com.YHVision.qiuzhike.model.dto.company.CompanyEditRequest;
import com.YHVision.qiuzhike.model.dto.company.CompanyQueryRequest;
import com.YHVision.qiuzhike.model.dto.company.CompanyUpdateRequest;
import com.YHVision.qiuzhike.model.entity.Company;
import com.YHVision.qiuzhike.model.entity.User;
import com.YHVision.qiuzhike.model.vo.CompanyVO;
import com.YHVision.qiuzhike.service.CompanyService;
import com.YHVision.qiuzhike.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * 企业接口
 *
 * @author <a href="">YHVision-小y</a>
 * @from <a href="todo">爱编程学习圈</a>
 */
@RestController
@RequestMapping("/company")
@Slf4j
public class CompanyController {

    @Resource
    private CompanyService companyService;

    @Resource
    private UserService userService;

    // region 增删改查

    /**
     * 创建企业
     *
     * @param companyAddRequest
     * @param request
     * @return
     */
    @PostMapping("/add")
    @AuthCheck(mustRole = {"admin","company"})
    public BaseResponse<Long> addCompany(@RequestBody CompanyAddRequest companyAddRequest, HttpServletRequest request) {
        ThrowUtils.throwIf(companyAddRequest == null, ErrorCode.PARAMS_ERROR);
        // todo 在此处将实体类和 DTO 进行转换
        Company company = new Company();
        BeanUtils.copyProperties(companyAddRequest, company);
        List<String> industry = companyAddRequest.getIndustry();
        if (industry != null) {
            company.setIndustry(JSONUtil.toJsonStr(industry));
        }
        // 数据校验
        companyService.validCompany(company, true);
        // todo 填充默认值
        User loginUser = userService.getLoginUser(request);
        company.setUserId(loginUser.getId());
        // 写入数据库
        boolean result = companyService.save(company);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        // 返回新写入的数据 id
        long newCompanyId = company.getId();
        return ResultUtils.success(newCompanyId);
    }

    /**
     * 删除企业
     *
     * @param deleteRequest
     * @param request
     * @return
     */
    @PostMapping("/delete")
    @AuthCheck(mustRole = {"admin","company"})
    public BaseResponse<Boolean> deleteCompany(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User user = userService.getLoginUser(request);
        long id = deleteRequest.getId();
        // 判断是否存在
        Company oldCompany = companyService.getById(id);
        ThrowUtils.throwIf(oldCompany == null, ErrorCode.NOT_FOUND_ERROR);
        // 仅本人或管理员可删除
        if (!oldCompany.getUserId().equals(user.getId()) && !userService.isAdmin(request)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        // 操作数据库
        boolean result = companyService.removeById(id);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(true);
    }

    /**
     * 更新企业（仅管理员可用）
     *
     * @param companyUpdateRequest
     * @return
     */
    @PostMapping("/update")
    @AuthCheck(mustRole = {"admin","company"})
    public BaseResponse<Boolean> updateCompany(@RequestBody CompanyUpdateRequest companyUpdateRequest) {
        if (companyUpdateRequest == null || companyUpdateRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        // todo 在此处将实体类和 DTO 进行转换
        Company company = new Company();
        BeanUtils.copyProperties(companyUpdateRequest, company);
        // 数据校验
        companyService.validCompany(company, false);
        // 判断是否存在
        long id = companyUpdateRequest.getId();
        Company oldCompany = companyService.getById(id);
        ThrowUtils.throwIf(oldCompany == null, ErrorCode.NOT_FOUND_ERROR);
        // 操作数据库
        boolean result = companyService.updateById(company);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(true);
    }

    /**
     * 根据 id 获取企业（封装类）
     *
     * @param id
     * @return
     */
    @GetMapping("/get/vo")
    public BaseResponse<CompanyVO> getCompanyVOById(long id, HttpServletRequest request) {
        ThrowUtils.throwIf(id <= 0, ErrorCode.PARAMS_ERROR);
        // 查询数据库
        Company company = companyService.getById(id);
        ThrowUtils.throwIf(company == null, ErrorCode.NOT_FOUND_ERROR);
        // 获取封装类
        return ResultUtils.success(companyService.getCompanyVO(company, request));
    }

    /**
     * 分页获取企业列表（仅管理员可用）
     *
     * @param companyQueryRequest
     * @return
     */
    @PostMapping("/list/page")
    @SaCheckRole(UserConstant.ADMIN_ROLE)
    public BaseResponse<Page<Company>> listCompanyByPage(@RequestBody CompanyQueryRequest companyQueryRequest) {
        long current = companyQueryRequest.getCurrent();
        long size = companyQueryRequest.getPageSize();
        // 查询数据库
        Page<Company> companyPage = companyService.page(new Page<>(current, size),
                companyService.getQueryWrapper(companyQueryRequest));
        return ResultUtils.success(companyPage);
    }

    /**
     * 分页获取企业列表（封装类）
     *
     * @param companyQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/list/page/vo")
    public BaseResponse<Page<CompanyVO>> listCompanyVOByPage(@RequestBody CompanyQueryRequest companyQueryRequest,
                                                               HttpServletRequest request) {
        long current = companyQueryRequest.getCurrent();
        long size = companyQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        // 查询数据库
        Page<Company> companyPage = companyService.page(new Page<>(current, size),
                companyService.getQueryWrapper(companyQueryRequest));
        // 获取封装类
        return ResultUtils.success(companyService.getCompanyVOPage(companyPage, request));
    }

    /**
     * 分页获取当前登录用户创建的企业列表
     *
     * @param companyQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/my/list/page/vo")
    public BaseResponse<Page<CompanyVO>> listMyCompanyVOByPage(@RequestBody CompanyQueryRequest companyQueryRequest,
                                                                 HttpServletRequest request) {
        ThrowUtils.throwIf(companyQueryRequest == null, ErrorCode.PARAMS_ERROR);
        // 补充查询条件，只查询当前登录用户的数据
        User loginUser = userService.getLoginUser(request);
        companyQueryRequest.setUserId(loginUser.getId());
        long current = companyQueryRequest.getCurrent();
        long size = companyQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        // 查询数据库
        Page<Company> companyPage = companyService.page(new Page<>(current, size),
                companyService.getQueryWrapper(companyQueryRequest));
        // 获取封装类
        return ResultUtils.success(companyService.getCompanyVOPage(companyPage, request));
    }

    /**
     * 编辑企业（给hr使用）
     *
     * @param companyEditRequest
     * @param request
     * @return
     */
    @PostMapping("/edit")
    @AuthCheck(mustRole = {"admin","company"})
    public BaseResponse<Boolean> editCompany(@RequestBody CompanyEditRequest companyEditRequest, HttpServletRequest request) {
        if (companyEditRequest == null || companyEditRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        // todo 在此处将实体类和 DTO 进行转换
        Company company = new Company();
        BeanUtils.copyProperties(companyEditRequest, company);
        List<String> industry = companyEditRequest.getIndustry();
        if (industry != null) {
            company.setIndustry(JSONUtil.toJsonStr(industry));
        }
        // 数据校验
        companyService.validCompany(company, false);
        User loginUser = userService.getLoginUser(request);
        // 判断是否存在
        long id = companyEditRequest.getId();
        Company oldCompany = companyService.getById(id);
        ThrowUtils.throwIf(oldCompany == null, ErrorCode.NOT_FOUND_ERROR);
        // 仅本人或管理员可编辑
        if (!oldCompany.getUserId().equals(loginUser.getId()) && !userService.isAdmin(loginUser)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        // 操作数据库
        boolean result = companyService.updateById(company);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(true);
    }

    // endregion
}
